#include "Application.hpp"


Application::Application()
  : m_camera(NULLPTR)
{
  /// Window
  aer::Window *pWin = createWindow( aer::Window::sDisplay_GL33_720p, "Island OpenGL 4.2" );
  pWin->setVerticalSync( true );
  
  
  
  /// Camera
  aer::View view( aer::Vector3( 0.0f, 25.0f, 0.0f),
                  aer::Vector3( 0.0f, 0.0f, 50.0f),
                  aer::Vector3( 0.0f, 1.0f, 0.0f) );
 
  float ratio = m_Window->getDisplay().getAspectRatio();
  aer::Frustum frustum( 60.0f, ratio, 0.1f, 1000.0f);

  m_camera = new aer::FreeCamera( view, frustum);
  m_camera->setMoveCoefficient( 1.2f );
  
  
  /// OpenGL settings
  glClearColor( 0.0f, 0.0f, 0.0f, 1.0f);
  
  glEnable( GL_DEPTH_TEST );
  glDepthFunc( GL_LEQUAL );
  
  //glEnable(GL_CULL_FACE);
  glCullFace( GL_BACK );
  
  
  /// Application data
  glswInit();
  glswSetPath( "../IslandGL4/data/shaders/", ".glsl"); // exec_path/../exec_name/shaders
  glswAddDirectiveToken("*", "#version 420 core");    
  
    m_terrain.init();
    m_skyDome.init();
  
  glswShutdown();
  
  
  CHECKGLERROR();
}


// -----------------------------------------------------------

void Application::resize(const aer::U32 width, const aer::U32 height)
{
  glViewport( 0, 0, width, height);
  
  CHECKGLERROR();
}

void Application::updateFrame()
{
  m_camera->update();
  
  
  if (aer::EventHandler::IsKeyPressed( sf::Keyboard::Escape )) 
  { 
    quit(); 
  }
  
  if (aer::EventHandler::IsKeyPressed( sf::Keyboard::F )) 
  { 
    printf("fps : %u\n", m_timer.getFPS()); 
  }
  
  if (aer::EventHandler::IsKeyDown( sf::Keyboard::W )) {
    glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
  } else {
    glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
    //aer::OpenGL::RenderMode( aer::FRONT_AND_BACK, aer::FILL);
  }
  
  CHECKGLERROR();
}

void Application::drawFrame()
{
  glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
  
  //aer::OpenGL::clear( aer::COLOR_BUFFER | aer::DEPTH_BUFFER );
  
  //aer::OpenGL::disableDepthTest();
  //aer::OpenGL::disableDepthWrite();
  
  
  glDisable( GL_CULL_FACE );  
  glDisable( GL_DEPTH_TEST );
  glDepthMask( GL_FALSE );
  
  m_skyDome.render( *m_camera, m_timer);
  
  
  glEnable( GL_DEPTH_TEST );
  glDepthMask( GL_TRUE );
  glEnable( GL_CULL_FACE );
  
  m_terrain.render( *m_camera );
  
  CHECKGLERROR();
}
